//
//  AudioTool.m
//  04-音效播放
//
//  Created by LC on 17/4/17.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "AudioTool.h"
#import <AVFoundation/AVFoundation.h>

static NSMutableDictionary  *cachedAudios;

@implementation AudioTool

+ (void)load {
    cachedAudios = [NSMutableDictionary dictionary];
}

// 1. 创建缓存对象
+ (void)playAudioWithName:(NSString *)name {
    
    // 2. 从缓存对象中获取soundID
    SystemSoundID soundID;
    if(cachedAudios[name]) {
        soundID = [cachedAudios[name] intValue];
    } else {
        
        // 3. 如果缓存中没有就创建并且添加到缓存中
        //播放音效URL
        NSURL *url = [[NSBundle mainBundle] URLForResource:name withExtension:nil];
        CFURLRef cfurl = (__bridge CFURLRef)(url);
        
        // 创建音效句柄
        // 第二个参数为输出参数
        AudioServicesCreateSystemSoundID(cfurl, &soundID);
        
        // 缓存创建好的对象
        cachedAudios[name] = @(soundID);
        
    }
    
    // 4. 播放音效
    AudioServicesPlaySystemSound(soundID);
    
    // 手机震动&播放音效
//    AudioServicesPlayAlertSound(soundID);
}

// 5. 释放音效
+ (void)clearAudios {
    for (NSString *name in cachedAudios) {
        SystemSoundID soundID = [cachedAudios[name] intValue];
        AudioServicesDisposeSystemSoundID(soundID);
        [cachedAudios removeObjectForKey:name];
    }
}

@end
